package cn.lxh.blog.service.impl;

import cn.lxh.blog.mapper.ArticleMapper;
import cn.lxh.blog.mapper.LikesMapper;
import cn.lxh.blog.service.ILikesService;
import cn.lxh.util.IPAddressUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * LikesServiceImpl业务层类
 */
@Service // 该类交给spring管理
public class LikesServiceImpl implements ILikesService {

    @Autowired
    private LikesMapper likesMapper;

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 根据ip获取点赞还是取消点赞
     * @param request
     */
    @Override
    public void getGoodByIp(HttpServletRequest request, Long articleId) {
        // 获取ip地址
        String ip = IPAddressUtils.getIpAdrress(request);
        // 根据ip和文章id查询点赞 (因为有多篇文章)
        Integer good = likesMapper.findGoodByIp(ip, articleId);
        if (good == null) { // 说明第一次点赞, 需要加入到数据库
            // good赋值为1
            good = 1;
            likesMapper.addIpGood(ip, good, articleId); // 加入到数据库
            articleMapper.addLike(articleId); // 文章点赞加1
        } else { // 不是第一次点赞了
            if (good == 0) { // 没有点赞, 点一下, 文章点赞加1, 并且good加1
                articleMapper.addLike(articleId);
                likesMapper.addGood(ip, articleId);
            } else { // 已经点赞, 点一下文章点赞减1, 并且good减1
                articleMapper.loseLike(articleId);
                likesMapper.loseGood(ip, articleId);
            }
        }
    }

    /**
     * 决定点赞图标颜色状态
     *
     * @param request
     * @return
     */
    @Override
    public Integer findGoodByIp(HttpServletRequest request, Long articleId) {
        // 获取ip地址
        String ip = IPAddressUtils.getIpAdrress(request);
        return likesMapper.findGoodByIp(ip, articleId);
    }
}
